package com.tidy.seed.interceptor;

import com.tidy.seed.annotation.NoToken;
import com.tidy.seed.common.StatusCode;
import com.tidy.seed.admin.system.entity.User;
import com.tidy.seed.exception.BaseException;
import com.tidy.seed.util.JwtUtils;
import com.tidy.seed.util.UserThreadLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    private static final String BEARER_PREFIX = "Bearer ";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------------LoginInterceptor执行-----------------");
        // 不是 controller 方法直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod hm = (HandlerMethod) handler;

        // 如果方法或类上有 @NoToken 注解，直接放行
        if (AnnotatedElementUtils.hasAnnotation(hm.getMethod(), NoToken.class)
                || AnnotatedElementUtils.hasAnnotation(hm.getBeanType(), NoToken.class)) {
            log.debug("接口 {} 被 @NoToken 标记，跳过登录校验", hm.getMethod().getName());
            return true;
        }

        String authorization = request.getHeader("Authorization");
        log.debug("请求 {} {} 的 Authorization 头：{}", request.getMethod(), request.getRequestURI(), authorization);

        User user = null;
        if (authorization != null && authorization.startsWith(BEARER_PREFIX)) {
            String token = authorization.substring(BEARER_PREFIX.length()).trim();
            try {
                user = JwtUtils.resolveJwt(token);
            } catch (Exception e) {
                log.warn("解析 JWT 失败: {}", e.getMessage());
            }
        } else {
            log.debug("Authorization 头缺失或不以 Bearer 开头");
        }
        if (user == null) {
            // 你可以改成统一返回 JSON，而不是抛异常让全局异常处理
            throw new BaseException(StatusCode.CODE_401, "未登录或令牌无效"); // 401
        }

        // 缓存用户
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
